<template>
  <div class="book-edit-container">
    <n-form
      ref="formRef"
      :model="bookForm"
      :rules="formRules"
      label-placement="top"
      require-mark-placement="right-hanging"
      size="large"
      class="book-form"
    >
      <div class="form-content">
        <div class="left-column">
          <div class="form-items">
            <n-form-item label="书籍标题" path="title">
              <n-input
                v-model:value="bookForm.title"
                placeholder="请输入书籍标题"
                maxlength="100"
                show-count
              />
            </n-form-item>
            
            <n-form-item label="书籍描述" path="description">
              <n-input
                v-model:value="bookForm.description"
                type="textarea"
                placeholder="请输入书籍描述"
                :autosize="{ minRows: 4, maxRows: 8 }"
                maxlength="500"
                show-count
              />
            </n-form-item>
            
            <n-form-item label="题材" path="genre">
              <n-select
                v-model:value="selectedGenres"
                :options="genreOptions"
                placeholder="请选择题材（可多选）"
                multiple
                :max-tag-count="3"
              />
            </n-form-item>
            
            <n-form-item label="状态" path="status">
              <n-select
                v-model:value="bookForm.status"
                :options="statusOptions"
                placeholder="选择书籍状态"
              />
            </n-form-item>

            <n-form-item class="button-item">
             <div class="button-container">
               <n-button type="primary" size="large" :loading="submitting" @click="handleSubmit">
                  {{ isEdit ? '更新' : '创建' }}
                </n-button>
              </div>
            </n-form-item>
          </div>
        </div>
        
        <div class="right-column">
          <n-form-item label="封面图片" path="coverImage">
            <div class="cover-image-wrapper" @click="generateCover">
              <img 
                v-if="bookForm.coverImage" 
                :src="getCoverImageUrl()" 
                alt="书籍封面" 
                class="cover-image"
              />
              <div v-else class="cover-placeholder">
                <n-icon size="48" :depth="3">
                  <ImageOutline />
                </n-icon>
                <n-text style="font-size: 16px; margin-top: 12px;">
                  点击生成封面
                </n-text>
                <n-text depth="3" style="margin-top: 8px; font-size: 12px;">
                  基于书籍标题和描述自动生成
                </n-text>
              </div>
              <div class="cover-overlay">
                <n-button type="primary" size="small" :loading="generatingCover">
                  {{ bookForm.coverImage ? '重新生成' : '生成封面' }}
                </n-button>
              </div>
            </div>
          </n-form-item>
          
          <!-- 选择器容器 -->
          <div class="selectors-container">
            <!-- 生图模型选择器 -->
            <div class="selector-item">
              <div class="selector-label">生图模型</div>
              <model-selector @select-model="handleModelSelect" :current-model="currentImageModel" direction="top" model-type="生图" />
            </div>
            
            <!-- 聊天模型选择器 -->
            <div class="selector-item">
              <div class="selector-label">聊天模型</div>
              <model-selector 
                @select-model="handleChatModelSelect" 
                :current-model="currentChatModel" 
                direction="top" 
                model-type="对话" 
              />
            </div>
            
            <!-- 提示词模板选择器 -->
            <div class="selector-item">
              <div class="selector-label">提示词模板</div>
              <n-select
                v-model:value="selectedTemplateId"
                :options="promptTemplateOptions"
                placeholder="选择提示词模板（可选）"
                clearable
                :loading="templatesLoading"
                @update:value="handleTemplateChange"
              />
            </div>
          </div>
        </div>
      </div>
    </n-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, inject } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  NButton,
  NInput,
  NSelect,
  NForm,
  NFormItem,
  NText,
  NIcon,
  useMessage
} from 'naive-ui'
import {
  ImageOutline
} from '@vicons/ionicons5'
import { bookService, type Book } from '../../book/services/book-service'
import { authService } from '../../auth/services/auth-service'
import BaseService from '../../shared/services/base-service'
import ModelSelector from '../../chat/components/ModelSelector.vue'
import { useModelStore } from '../../shared/stores/model'
import { usePromptStore } from '../../shared/stores/prompt'

const router = useRouter()
const route = useRoute()
const message = useMessage()
const modelStore = useModelStore()
const promptStore = usePromptStore()

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 处理模型选择
const handleModelSelect = (model: number) => {
  currentImageModel.value = model;
  // 更新modelStore中的currentImageModel
  modelStore.setCurrentImageModel(model);
};

// 处理聊天模型选择
const handleChatModelSelect = (model: number) => {
  currentChatModel.value = model;
  // 更新modelStore中的currentChatModel
  modelStore.setCurrentChatModel(model);
};

// 状态变量
const currentImageModel = computed({
  get: () => modelStore.currentImageModel,
  set: (val: number) => {
    modelStore.setCurrentImageModel(val);
  }
});

const currentChatModel = computed({
  get: () => modelStore.currentChatModel,
  set: (val: number) => {
    modelStore.setCurrentChatModel(val);
  }
});

// 提示词模板相关
const selectedTemplateId = ref<number | null>(null)
const templatesLoading = ref(false)
const promptTemplateOptions = ref<Array<{label: string, value: number}>>([])

// 初始化时从Pinia获取之前选择的模板ID
const initSelectedTemplateId = () => {
  selectedTemplateId.value = promptStore.getCoverSelectedTemplateId()
}

// 处理提示词模板选择变化
const handleTemplateChange = (value: number | null) => {
  // 保存用户选择的模板ID到Pinia
  promptStore.saveCoverSelectedTemplateId(value)
}

// 题材相关
const selectedGenres = ref<string[]>([])
const genreOptions = [
  { label: '穿越', value: '穿越' },
  { label: '武侠', value: '武侠' },
  { label: '都市', value: '都市' },
  { label: '古风', value: '古风' },
  { label: '言情', value: '言情' },
  { label: '世情', value: '世情' },
  { label: '玄幻', value: '玄幻' },
  { label: '科幻', value: '科幻' },
  { label: '仙侠', value: '仙侠' },
  { label: '历史', value: '历史' },
  { label: '军事', value: '军事' },
  { label: '游戏', value: '游戏' },
  { label: '体育', value: '体育' },
  { label: '悬疑', value: '悬疑' },
  { label: '灵异', value: '灵异' },
  { label: '二次元', value: '二次元' },
  { label: '现实', value: '现实' },
  { label: '轻小说', value: '轻小说' }
]

// 加载提示词模板
const loadPromptTemplates = async () => {
  templatesLoading.value = true
  try {
    const { promptService } = await import('../../prompt/services/prompt-service')
    const response = await promptService.getPromptTemplates()
    
    if (response.code === 0 && response.data) {
      promptTemplateOptions.value = response.data.map((template: any) => ({
        label: template.name,
        value: template.id
      }))
      
      // 确保之前选择的模板ID在选项中存在
      const savedTemplateId = promptStore.getCoverSelectedTemplateId()
      if (savedTemplateId !== null) {
        const exists = promptTemplateOptions.value.some(option => option.value === savedTemplateId)
        if (exists) {
          // 如果之前选择的模板ID在当前选项中，则设置为选中状态
          selectedTemplateId.value = savedTemplateId
        } else {
          // 如果之前选择的模板ID不在当前选项中，则清除选择
          selectedTemplateId.value = null
          promptStore.saveCoverSelectedTemplateId(null)
        }
      }
    }
  } catch (error) {
    console.error('加载提示词模板失败:', error);
    message.error('加载提示词模板失败')
  } finally {
    templatesLoading.value = false
  }
}

// 响应式数据
const submitting = ref(false)
const generatingCover = ref(false)
const formRef = ref()

// 状态选项
const statusOptions = [
  { label: '草稿', value: 0 },
  { label: '已发布', value: 1 },
  { label: '已下架', value: 2 }
]

// 表单数据
const bookForm = reactive<Book>({
  title: '',
  description: '',
  coverImage: '',
  status: 0,
  userId: 0
})

// 表单验证规则
const formRules = {
  title: {
    required: true,
    message: '请输入书籍标题',
    trigger: 'blur'
  },
  description: {
    required: true,
    message: '请输入书籍描述',
    trigger: 'blur'
  }
}

// 获取封面图片URL
const getCoverImageUrl = () => {
  if (!bookForm.coverImage) return ''
  
  // 如果是外部URL（http开头），直接返回
  if (bookForm.coverImage.startsWith('http')) {
    return bookForm.coverImage
  }
  
  // 如果是相对路径（/开头），构建完整的访问URL
  if (bookForm.coverImage.startsWith('/')) {
    return `${BaseService.getApiUrl()}${bookForm.coverImage}`
  }
  
  // 如果是uploads/开头的路径，直接添加API前缀
  if (bookForm.coverImage.startsWith('uploads/')) {
    return `${BaseService.getApiUrl()}/${bookForm.coverImage}`
  }
  
  // 其他情况，使用默认的图片访问路径
  return `${BaseService.getApiUrl()}/book/image/${bookForm.id}/${bookForm.coverImage.split('/').pop()}`
}

// 生成封面
const generateCover = async () => {
  if (!bookForm.title.trim()) {
    message.warning('请先输入书籍标题')
    return
  }
  
  generatingCover.value = true
  try {
    // 使用Pinia中的方法获取处理后的提示词（已替换占位符）
    const prompt = promptStore.getProcessedCoverPrompt(bookForm.title, bookForm.description)
    
    // 保存当前使用的提示词模板到Pinia
    promptStore.saveCoverPromptTemplate(prompt)
    // 保存当前选择的模板ID到Pinia
    promptStore.saveCoverSelectedTemplateId(selectedTemplateId.value)
    
    // 调用API生成封面
    const res = await bookService.generateBookCover({
      modelId: currentImageModel.value, // 使用当前选择的生图模型
      message: prompt,
      num: 1,
      width: 200,
      height: 280,
      weight: 0.8,
      chatModelId: currentChatModel.value, // 聊天模型ID
      sysTemplateId: selectedTemplateId.value ?? 0 // 提示词模板ID
    })
    
    if (res.code === 0 && res.data) {
      // 设置封面图片URL
      bookForm.coverImage = res.data
      message.success('封面生成成功')
    } else {
      message.error(res.msg || '封面生成失败')
    }
  } catch (error) {
    console.error('生成封面失败:', error)
    message.error('生成封面失败')
  } finally {
    generatingCover.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
  } catch (error) {
    return
  }
  
  submitting.value = true
  try {
    // 将选中的多个题材用逗号分隔
    const genreString = selectedGenres.value.join(',')
    
    let response
    if (isEdit.value) {
      // 更新书籍
      response = await bookService.updateBook({
        ...bookForm,
        id: Number(route.params.id),
        genre: genreString
      })
    } else {
      // 创建书籍
      response = await bookService.createBook({
        ...bookForm,
        genre: genreString
      })
    }
    
    if (response.code === 0) {
      message.success(isEdit.value ? '更新成功' : '创建成功')
      
      // 在标签页环境中，关闭当前标签页而不是跳转
      const closeTab = inject<() => void>('closeTab')
      if (closeTab) {
        closeTab()
      } else {
        // 如果没有标签页系统，则使用路由跳转
        router.push('/books')
      }
    } else {
      message.error(response.msg || '操作失败')
    }
  } catch (error) {
    message.error('操作失败')
    console.error('提交表单失败:', error)
  } finally {
    submitting.value = false
  }
}

// 加载书籍数据（编辑模式）
const loadBookData = async () => {
  if (!isEdit.value) return
  
  try {
    const bookId = Number(route.params.id)
    const response = await bookService.getBookById(bookId)
    
    if (response.code === 0 && response.data) {
      const book = response.data
      bookForm.title = book.title
      bookForm.description = book.description
      bookForm.coverImage = book.coverImage || ''
      bookForm.status = book.status
      bookForm.userId = book.userId
      
      // 处理题材字段，将逗号分隔的字符串转换为数组
      if (book.genre) {
        selectedGenres.value = book.genre.split(',').map((genre: string) => genre.trim())
      }
    } else {
      message.error('获取书籍信息失败')
      // 在标签页环境中，关闭当前标签页而不是跳转
      const closeTab = inject<() => void>('closeTab')
      if (closeTab) {
        closeTab()
      } else {
        // 如果没有标签页系统，则使用路由跳转
        router.push('/books')
      }
    }
  } catch (error) {
    message.error('获取书籍信息失败')
    console.error('获取书籍信息失败:', error)
    // 在标签页环境中，关闭当前标签页而不是跳转
    const closeTab = inject<() => void>('closeTab')
    if (closeTab) {
      closeTab()
    } else {
      // 如果没有标签页系统，则使用路由跳转
      router.push('/books')
    }
  }
}

// 初始化
onMounted(async () => {
  // 获取当前用户ID
  const userId = authService.getOrCreateUserId()
  if (userId) {
    bookForm.userId = userId
  }
  
  // 先从Pinia获取之前选择的模板ID
  initSelectedTemplateId()
  
  // 加载提示词模板（这会自动设置之前选择的模板）
  await loadPromptTemplates()
  
  // 加载模型数据
try {
  console.log('BookEdit: 开始加载模型数据')
  
  // 检查用户认证状态
  const { authPromptService } = await import('../../auth/services/auth-prompt-service')
  const isLoggedIn = await authPromptService.checkAndPromptLogin()
  console.log('BookEdit: 用户认证状态', isLoggedIn)
  
  if (!isLoggedIn) {
    console.warn('BookEdit: 用户未登录，无法加载模型数据')
    return
  }
  
  // 加载模型数据
  await modelStore.loadModels()
  console.log('BookEdit: 模型数据加载完成', modelStore.models)
  
  // 检查是否有可用的生图模型
  const imageModels = modelStore.getModelsByTag('生图')
  console.log('BookEdit: 可用的生图模型', imageModels)
  
  // 检查是否有可用的聊天模型
  const chatModels = modelStore.getModelsByTag('对话')
  console.log('BookEdit: 可用的聊天模型', chatModels)
  
  // 如果没有可用的模型，显示警告
  if (imageModels.length === 0) {
    console.warn('BookEdit: 没有可用的生图模型')
    message.warning('没有可用的生图模型，请联系管理员')
  }
  
  if (chatModels.length === 0) {
    console.warn('BookEdit: 没有可用的聊天模型')
    message.warning('没有可用的聊天模型，请联系管理员')
  }
} catch (error) {
  console.error('BookEdit: 加载模型数据失败', error)
  message.error('加载模型数据失败，请检查网络连接或联系管理员')
}
  
  // 如果是编辑模式，加载书籍数据
  if (isEdit.value) {
    await loadBookData()
  }
})
</script>

<style scoped>
.book-edit-container {
  width: 100%;
  height: calc(100vh - 50px);
  display: flex;
  flex-direction: column;
  background-color: #f8f9fa;
  box-sizing: border-box;
  overflow: hidden;
}

.title-section {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.back-button {
  margin-right: 16px;
  padding: 6px 12px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.book-form {
  flex: 1;
  background-color: #fff;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.form-content {
  display: flex;
  flex: 1;
  gap: 24px;
  overflow: hidden;
  min-height: 0;
}

.left-column {
  flex: 3;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

.left-column .form-items {
  flex: 1;
  overflow-y: auto;
  padding-right: 8px;
  margin-bottom: 4px;
}

.right-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding-top: 16px;
}

.form-actions {
  margin-top: 8px;
  padding-top: 0;
  padding-bottom: 0;
  display: flex;
  justify-content: center;
  gap: 16px;
}

.book-form :deep(.n-form-item) {
  margin-bottom: 12px;
  width: 100%;
}

.button-item {
  margin-top: 8px;
  margin-bottom: 0;
}

.button-container {
  display: flex;
  justify-content: center;
  width: 100%;
}

/* 压缩表单项反馈包装器的高度 */
.book-form :deep(.n-form-item-feedback-wrapper) {
  min-height: 16px;
  margin-top: 2px;
}

/* 调整表单项内容区域间距 */
.book-form :deep(.n-form-item-blank) {
  margin-bottom: 4px;
}



.book-form :deep(.n-form-item-label) {
  font-weight: 500;
  margin-bottom: 4px;
}

.book-form :deep(.n-input), 
.book-form :deep(.n-input-number),
.book-form :deep(.n-select),
.book-form :deep(.n-textarea) {
  transition: all 0.3s ease;
  width: 100%;
}

.book-form :deep(.n-input:hover), 
.book-form :deep(.n-input-number:hover),
.book-form :deep(.n-select:hover),
.book-form :deep(.n-textarea:hover) {
  box-shadow: 0 0 0 2px rgba(24, 160, 88, 0.1);
}

.book-form :deep(.n-input.n-input--focus), 
.book-form :deep(.n-input-number.n-input-number--focus),
.book-form :deep(.n-select.n-select--focus),
.book-form :deep(.n-textarea.n-input--focus) {
  box-shadow: 0 0 0 2px rgba(24, 160, 88, 0.2);
}

.form-actions :deep(.n-button) {
  min-width: 120px;
  height: 40px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.form-actions :deep(.n-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.form-actions :deep(.n-button--default-type) {
  background-color: #f5f5f5;
  border: 1px solid #e0e0e0;
  color: #333;
}

.form-actions :deep(.n-button--default-type:hover) {
  background-color: #eeeeee;
  border-color: #d0d0d0;
}

.form-actions :deep(.n-button--primary-type) {
  background: linear-gradient(135deg, #18a058 0%, #36ad6a 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(24, 160, 88, 0.3);
}

.form-actions :deep(.n-button--primary-type:hover) {
  background: linear-gradient(135deg, #36ad6a 0%, #18a058 100%);
  box-shadow: 0 4px 16px rgba(24, 160, 88, 0.4);
}

/* 封面相关样式 */
.cover-image-wrapper {
  position: relative;
  width: 200px;
  height: 280px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cover-image-wrapper:hover {
  border-color: #18a058;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

.cover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.cover-image-wrapper:hover .cover-overlay {
  opacity: 1;
}

/* 模型选择器样式 */
.selectors-container {
  width: 100%;
  margin-top: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.selector-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  width: 100%;
}

.selector-label {
  font-size: 12px;
  color: #999;
  margin-bottom: 6px;
  font-weight: 500;
}

/* 滚动条样式 */
.form-items::-webkit-scrollbar {
  width: 6px;
}

.form-items::-webkit-scrollbar-track {
  background: transparent;
}

.form-items::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.form-items::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.2);
}
</style>